package com.woniuxy.carrental.controller;

import com.woniuxy.carrental.entity.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xilei
 * @create 2021-10-02 上午 11:25
 */

@RestController
@Controller
@CrossOrigin
public class UploadDownCarpartController {
    @Value("${uploaddown.carpart.ipaddresss}")
    private String ipaddresss;
    @PostMapping("/uploadcarpart")
    @ResponseBody
        public ResponseResult upload(@RequestParam(value = "carpart_picture",required = false)MultipartFile carpart_picture, HttpServletRequest request) {
        System.out.println(carpart_picture);

        //获取原始文件名称(包含格式)
        String originalFileName = carpart_picture.getOriginalFilename();
        System.out.println("原始汽配图片文件名称：" + originalFileName);

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        System.out.println("文件类型：" + type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(d);
        String fileName = date + name + "." + type;
        System.out.println("新汽配图片文件名称：" + fileName);

        //在指定路径下创建一个文件
        File targetFile = new File("D:\\333\\imagesscarpart", fileName);
        System.out.println("文件的保存路径："+"D:\\333\\imagesscarpart\\"+fileName);
        //将文件保存到服务器指定位置
        try {
            carpart_picture.transferTo(targetFile);
            System.out.println("上传汽配图片成功");
            //将文件在服务器的存储路径返回
            return new ResponseResult(null, 222, ipaddresss+fileName);
        } catch (IOException e) {
            System.out.println("上传汽配图片失败");
            e.printStackTrace();
            return new ResponseResult(null,200,"上传汽配图片失败");
        }
    }

}
